package org.huamoxi.inventory;

import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.huamoxi.entity.MarketItem;
import org.huamoxi.util.DataSQLUtil;
import org.huamoxi.util.InventoryUtil;

import java.sql.Connection;

public class MarketInventory {

    public void openMarketInventory (Player player, FileConfiguration config, Integer current, Integer maxPage, Connection dbConnection) {
        Inventory marketInventory = Bukkit.createInventory(null, 54, config.getString("market.title"));
        try {
            int pageSize = config.getInt("market.pageSize");
            // 设置商品inventory
            DataSQLUtil.setInventoryByCurrent(player, true, marketInventory, config, current, pageSize, dbConnection);
        } catch (Exception e) {
            e.printStackTrace();
        }

        InventoryUtil.setMarketPaper(marketInventory, config, current, maxPage);

        InventoryUtil.setMarketSign(marketInventory, config);

        InventoryUtil.setGlassPane(marketInventory, config);

        // 打开容器
        player.openInventory(marketInventory);
    }

    /**
     * 出售物品
     */
    public void sellItem (Player player, MarketItem marketItem, int amount, int number, FileConfiguration config, Connection dbConnection) {
        // 移除玩家手上的物品
        if (amount == number) {
            player.getInventory().setItemInMainHand(null);
        } else {
            player.getInventory().getItemInMainHand().setAmount(amount - number);
        }
        // 记录数据
        String sellItemSQL = "insert into tb_market_item(type, title, lore, price, quantity, durability, maxDurability, enchantDescription, category, state, playerUID, validity, sort) " +
                "values ('" + marketItem.getType() +
                "','" + (marketItem.getTitle().length() > 0 ? marketItem.getTitle() : "") +
                "','" + (marketItem.getLore().length() > 0 ? marketItem.getLore() : "") +
                "'," + marketItem.getPrice() +
                "," + marketItem.getQuantity() +
                "," + marketItem.getDurability() +
                "," + marketItem.getMaxDurability() +
                ",'" + marketItem.getEnchantDescription() +
                "'," + marketItem.getCategory() +
                "," + marketItem.getState() +
                ",'" + marketItem.getPlayerUID() +
                "'," + marketItem.getValidity() +
                "," + marketItem.getSort() +
                ")";
        int i = DataSQLUtil.insertSQL(dbConnection, sellItemSQL);
        if (i > 0) {
            player.sendMessage(config.getString("market.name")
                    + config.getString("notice.sellSuccessMsg"));
        } else {
            player.sendMessage(config.getString("market.name")
                    + config.getString("notice.sellFairMsg"));
        }
    }
}
